import { Modal, message } from 'antd';
import axios from 'axios';
import type { AxiosError, AxiosResponse } from 'axios';
// import store from '@/store'
// create an axios instance
const request = axios.create({
    // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    baseURL: 'http://localhost:3002/', // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 50000, // request timeout
});

// request interceptor
request.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('token');
        if (token === null) {
            return config;
        }
        config.headers['Authorization'] = `Bearer ${token}`;
        return config;
    },
    (error: any) => {
        // do something with request error
        return Promise.reject(error);
    },
);

// response interceptor
request.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    (res: AxiosResponse) => {
        const token = res.headers.token;
        if (token) {
            localStorage.setItem('token', token);
        }
        if (res.data.statusCode === 400) {
            message.error(res.data.message);
        }

        return res.data;
    },
    (error: AxiosError<any>) => {
        let res = error.response;
        if (res?.data.statusCode === 403) {
            const handleConfirm = () => {
                // 跳转到登录页面
                window.location.href = '/login';
            };
            const handleCancel = () => {
                // 处理取消操作
            };
            Modal.confirm({
                title: '您还没有登录账号,是否登录?',
                onOk: handleConfirm,
                onCancel: handleCancel,
                okText: '确定',
                cancelText: '取消',
            });
        }
        return res?.data;
    },
);
export default request;
